<template>
    <div class="login_page">
        <div class="login_logo_box">
            <div class="login_logo"></div>
        </div>

        <div class="login_text">
            <h1>登录OhBen</h1>
        </div>
        <v-sheet class="mx-auto" width="300">
            <v-form ref="form">
                <v-text-field v-model="telephone" :counter="11" :rules="telephoneRules" label="手机号"
                    required></v-text-field>
                <v-text-field v-model="password" :rules="passwordRules" label="密码" type="password"
                    required></v-text-field>

                <div class="d-flex flex-column">
                    <v-btn class="mt-2" color="success" block @click="validate">
                        登录
                    </v-btn>
                    <div class="mt-4 login_footer">
                        <span @click="register">还没有账号？</span>
                        <span @click="forgetPassword">忘记密码？</span>
                    </div>
                </div>
            </v-form>
        </v-sheet>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios'; // 引入axios用于发送HTTP请求
import { useUserStore } from '@/stores/user'; // 引入 Pinia store

const form = ref(null);
const telephone = ref('15020221010');
const password = ref('kinit2022');
const accessToken = ref('');
const refreshToken = ref('');
const userInfo = ref(null);
const userStore = useUserStore(); // 使用 Pinia store

const telephoneRules = [
    v => !!v || '手机号为必填项',
    v => (v && v.length == 11) || '请输入正确的手机号码',
];

const passwordRules = [
    v => !!v || '密码为必填项',
    v => (v && v.length >= 6) || '密码不少于6位',
];

const validate = async () => {
    const { valid } = await form.value.validate();
    if (valid) {
        login();
    }
};

const login = () => {
    axios.post('/api/auth/login', {
        telephone: telephone.value,
        password: password.value
    })
        .then(response => {
            // 登录成功后获取access_token和refresh_token
            if (response.data.code === 200 && response.data.message === 'success') {
                const { access_token, refresh_token } = response.data.data;// 注意这里是从 response.data.data 中解构
                accessToken.value = access_token;
                refreshToken.value = refresh_token;

                // 设置本地存储和全局请求头
                setAuthTokens(access_token, refresh_token);

                // 登录成功后获取用户信息
                return axios.get('/api/vadmin/auth/user/admin/current/info', { headers: { 'Authorization': `bearer ${access_token}` } })
                    .then(response => {
                        const { data } = response.data;
                        userInfo.value = data;
                        console.log(data);
                        userStore.login(data, access_token, refresh_token); // 更新 Pinia store 中的登录状态
                        // 跳转到首页
                        window.location.href = '/';
                    });
            } else {
                // 处理登录失败的逻辑
                console.error('登录失败', response.data.message);
            }
        })
        .catch(error => {
            console.error('登录或获取用户信息失败', error);
            // 处理登录或获取用户信息失败后的逻辑
        });
};

const setAuthTokens = (access_token, refresh_token) => {
    localStorage.setItem('access_token', access_token);
    localStorage.setItem('refresh_token', refresh_token);
    axios.defaults.headers.common['Authorization'] = `bearer ${access_token}`;
};


const register = () => {
    // 注册逻辑
    // 跳转到注册页面
    window.location.href = '/register';
};

const forgetPassword = () => {
    // 忘记密码逻辑
    // 跳转到忘记密码页面
    window.location.href = '/forget-password';
};
</script>


<style scoped>
.login_page {
    background-color: rgb(255, 255, 255);
    /* background:url('@/assets/images/login_bg.jpg') */
    height: 100vh;

}

.login_logo_box {
    display: flex;
    /* 水平居中对齐Flex容器中的子元素 */
    justify-content: center;
    /* 垂直居中对齐Flex容器中的子元素 */
    align-items: center;
    padding: 32px 0 24px 0;
}

.login_logo {
    /* 设置高度和宽度为48px */
    height: 48px;
    width: 48px;
    /* 设置背景图片为login_logo.svg，并使用cover模式覆盖整个元素 */
    background-image: url('@/assets/svg/login_logo.svg');
    background-size: cover;
    /* 将背景图片居中显示 */
    background-position: center;
}

/* 登录文本样式 */
.login_text {
    font-family: 'Open Sans', sans-serif;
    /* 字体 */
    font-size: 24px;
    /* 字体大小 */
    font-weight: 300;
    /* 字体粗细 */
    text-align: center;
    /* 文本对齐方式 */
    letter-spacing: -.5px;
    /* 字母间距 */
    margin-bottom: 1rem;
    /* 底部外边距 */
}

.login_footer {
    display: flex;
    justify-content: space-between;
}
</style>